<template>
  <div class="note-container">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="笔记标题">
          <el-input 
            v-model="searchForm.title" 
            placeholder="请输入笔记标题" 
            clearable
            style="width: 200px;">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchNotes">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="content-card">
      <template #header>
        <div class="card-header">
          <span>我的笔记管理</span>
          <div>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">批量删除</el-button>
            <el-button type="primary" @click="showAddDialog">添加笔记</el-button>
          </div>
        </div>
      </template>

      <el-table :data="notes" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="笔记标题" width="200" />
        <el-table-column prop="createdTime" label="创建时间" width="180" />
        <el-table-column prop="updatedTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteNoteHandler(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
    >
      <el-form :model="currentItem" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="笔记标题" prop="title">
          <el-input 
            v-model="currentItem.title" 
            placeholder="请输入笔记标题" 
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="笔记内容" prop="content">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden;"
              v-model="currentItem.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNote">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllNotes,
  addNote,
  updateNote,
  deleteNote,
  searchNotes as apiSearchNotes,
  deleteNotes
} from '@/api/note'
import type { Note } from '@/types/note'

// 富文本编辑器相关导入
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { createEditorRef, getEditorConfig, getToolbarConfig, createEditorCallback } from '@/utils/editorUtils'

// 数据相关
const notes = ref<Note[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedIds = ref<number[]>([])

// 富文本编辑器相关
const editorRef = createEditorRef()
const mode = 'default'
const editorConfig = getEditorConfig('请输入笔记内容...', '我的笔记')
const toolbarConfig = getToolbarConfig()
const handleCreated = createEditorCallback(editorRef)

// 搜索表单
const searchForm = reactive({
  title: ''
})

// 当前编辑项
const currentItem = reactive<Note>({
  id: undefined,
  title: '',
  content: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入笔记标题', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入笔记内容', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref()

// 截取文本显示
const truncateText = (text: string, length: number) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 获取所有笔记
const fetchNotes = async () => {
  try {
    const res: any = await getAllNotes()
    if (res.code === 200) {
      notes.value = res.data
      total.value = res.data.length
    } else {
      ElMessage.error(res.message || '获取笔记失败')
    }
  } catch (error: any) {
    ElMessage.error('获取笔记失败: ' + (error.message || error))
  }
}

// 搜索笔记
const searchNotes = async () => {
  try {
    const res: any = await apiSearchNotes({
      title: searchForm.title
    })
    if (res.code === 200) {
      notes.value = res.data
      total.value = res.data.length
    } else {
      ElMessage.error(res.message || '搜索笔记失败')
    }
  } catch (error: any) {
    ElMessage.error('搜索笔记失败: ' + (error.message || error))
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  fetchNotes()
}

// 显示添加对话框
const showAddDialog = () => {
  // 重置表单
  Object.assign(currentItem, {
    id: undefined,
    title: '',
    content: ''
  })
  dialogTitle.value = '添加笔记'
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (item: Note) => {
  // 填充表单数据
  Object.assign(currentItem, item)
  dialogTitle.value = '编辑笔记'
  dialogVisible.value = true
}

// 保存笔记
const saveNote = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let res: any
        if (currentItem.id) {
          // 更新
          res = await updateNote(currentItem)
        } else {
          // 添加
          res = await addNote(currentItem)
        }
        
        if (res.code === 200) {
          ElMessage.success(res.message || (currentItem.id ? '更新成功' : '添加成功'))
          dialogVisible.value = false
          fetchNotes()
        } else {
          ElMessage.error(res.message || (currentItem.id ? '更新失败' : '添加失败'))
        }
      } catch (error: any) {
        ElMessage.error((currentItem.id ? '更新失败' : '添加失败') + ': ' + (error.message || error))
      }
    }
  })
}

// 删除笔记
const deleteNoteHandler = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个笔记吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res: any = await deleteNote(id)
    if (res.code === 200) {
      ElMessage.success(res.message || '删除成功')
      fetchNotes()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.message || error))
    }
  }
}

// 分页相关
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchNotes()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchNotes()
}

// 处理选择变化
const handleSelectionChange = (selection: Note[]) => {
  selectedIds.value = selection.map(item => item.id as number)
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一个笔记')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个笔记吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res: any = await deleteNotes(selectedIds.value)
    if (res.code === 200) {
      ElMessage.success(res.message || '批量删除成功')
      fetchNotes()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + (error.message || error))
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchNotes()
})
</script>

<style scoped>
.note-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-card :deep(.el-form-item) {
  margin-right: 20px;
}

.search-card :deep(.el-select) {
  width: 200px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>